<?php

    class localization {
        protected $lang;
        protected $supported_langs;
        protected $default_lang;
        protected $k_delimiter = "=";
        
        // Initialize object and selects correct language
        function __construct($languages, $defaultlang) {
            $this->supported_langs = $languages;
            $this->default_lang = $defaultlang;
            $this->lang = $this->default_lang;
        }
        
        
        // Search for user language
        function find_lang() {
            if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {
                $languages = strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]);
                $languages = str_replace(' ', '', $languages);
                $languages = explode(",", $languages);
                
                $i = 0;
                foreach ($languages as $language_list) {
                    $user_languages[$i] = substr( $language_list, 0, 2 );
                    $i++;
                }
                
                for ($i = 0; $i < count($user_languages); $i++) {
                    for ($j = 0; $j < count($this->supported_langs); $j++) {
                        if (strcmp($user_languages[$i], $this->supported_langs[$j]) == 0) {
                            return $user_languages[$i];
                        }
                    }
                }
            }
            
            return $this->default_lang;
        }
        
        // Load the label file corresponding to correct language
        // and returns all labels as an array. 
        function load_labels($label_file_template) {
            $this->lang = $this->find_lang();
            
            $label_file = str_replace('$1', $this->lang, $label_file_template);
            $label_list = array();
            
            $lines = file($label_file,  FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            foreach ($lines as $l) {
                list($lbl_code, $lbl_text) = explode($this->k_delimiter, $l);
                $label_list[$lbl_code] = $lbl_text;
            }
            
            return $label_list;
            
        }
        
    }

?>
